package com.offcn.test;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.Test;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtEncodeAndDeCode {

    @Test
    public void createJwt(){
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId("123456")  // jwt的id
                .setSubject("xiaobai") // sub 存储的内容
                .setIssuer("小花") // 签发人
                .setIssuedAt(new Date()) // 令牌的签发时间
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 100))  // 令牌的过期时间
                .signWith(SignatureAlgorithm.HS256, "ujiuye");

        // 自定义格式
        Map<String, Object> map = new HashMap<>();
        map.put("username","小白白");
        map.put("password","123456789");
        jwtBuilder.addClaims(map); // 添加自定义属性值

        // 替换自定义属性值
//        jwtBuilder.setClaims(map);

        String jwt = jwtBuilder.compact();
        System.out.println("生成jwt的字符串:" + jwt);
    }

    @Test
    public void decodeJwt(){
        String jwt = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMjM0NTYiLCJzdWIiOiJ4aWFvYmFpIiwiaXNzIjoi5bCP6IqxIiwiaWF0IjoxNjQ2NzAxOTkxLCJleHAiOjE2NDY3MDIwOTEsInBhc3N3b3JkIjoiMTIzNDU2Nzg5IiwidXNlcm5hbWUiOiLlsI_nmb3nmb0ifQ.xn6L56DTkvqnG_5a8K111HekkrWCC_cGGSz6USdNH_0";
        Claims claims = Jwts.parser()
                .setSigningKey("ujiuye")
                .parseClaimsJws(jwt)
                .getBody();
        System.out.println("解密之后的结果:" + claims);
    }
}
